package com.stlm2.dems.recharge.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.FluxDao;
import com.stlm2.dems.dao.FmsFlowDao;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.user.service.AccountService;
import com.stlm2.dems.util.CoreLogic;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.recharge.entity.Recharge;
import com.stlm2.dems.recharge.dao.RechargeDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("rechargeService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class RechargeService extends BaseServiceImpl<Recharge> {

	@Resource
	private RechargeDao rechargeDao;
	@Resource
	private FmsFlowDao fmsFlowDao;
	@Resource
	private AccountService accountService;
	@Resource
	private UserDao userDao;
	@Resource
	private CoreLogic coreLogic;
	@Resource
	private FluxDao fluxDao;
	@Override
	protected BaseDao <Recharge> getDao() {
		return rechargeDao;
	}

	public Recharge addRecharge(Integer userid,String money,Integer fluxId,Integer flux,String phone) {
		Flux flux1=fluxDao.getById(fluxId);
		Recharge recharge =new Recharge();
		recharge.setUserId(userid);
		recharge.setCreateTime(new Date());
		recharge.setCode("CZ"+userid+new Date().getTime());
		recharge.setMoney(flux1.getMoney());
		recharge.setOrderState(OrderState.Create);
		recharge.setFluxId(fluxId);
		recharge.setFlux(flux1.getFlux());
		recharge.setPhone(phone);
		addEntity(recharge);
		return recharge;
	}
	public Recharge getByCode(String code){
		return rechargeDao.getByCode(code);
	}

	public Recharge pay(Recharge temp, String tno,PayChannel payChannel) {

		Recharge recharge = rechargeDao.getByCode(temp.getCode());//数据库加悲观锁，防止重复支付
		System.out.println("获取实例："+recharge.getCode());
		synchronized (recharge) {
			if(!OrderState.Create.equals(recharge.getOrderState()))
				return recharge;

			User user=userDao.getById(recharge.getUserId());
			if (StringUtils.isBlank(tno))
				return null;
			recharge.setTransactionNo(tno);
			recharge.setPayTime(new Date());
			recharge.setPayChannel(payChannel);
			recharge.setOrderState(OrderState.Payment);
			System.out.println("支付更改时间"+recharge.getPayTime());
			rechargeDao.modify(recharge);

			coreLogic.addFundsFlow(user.getId(),recharge.getMoney(), FlowSource.Buy, FlowType.Reduce, null, recharge.getCode());//资金流水
			coreLogic.addFundsFlow(user.getId(),recharge.getMoney(), FlowSource.GiveIntegral, FlowType.Add, null, recharge.getCode());//积分流水
			coreLogic.changeRemainJiFen(user.getId(),recharge.getMoney(),FlowSource.GiveIntegral,FlowType.Add);//增加积分

		}
		return recharge;
	}

	public List<Recharge> getByUserId(Integer userid) {
		return rechargeDao.getByUserId(userid);
	}

	public List<Recharge> getOverRechageByUserId(Integer userid) {
		return rechargeDao.getOverRechageByUserId(userid);
	}


	public String getUserRechargeRecord(ModelMap map ,String page, String token ,String  userName ,String stateValue,String payChannelValue,String code,String transactionNo){
		Recharge recharge =new Recharge();
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}

		if(NumberUtils.isNumber(userName)){
			User user=userDao.getByName(userName.trim());
			if(user!=null){
				recharge.setUserId(user.getId());
			}
		}
		if(!StringUtils.isEmpty(code)){
			recharge.setCode(code.trim());
		}
		if(NumberUtils.isNumber(stateValue)){
			recharge.setOrderStateValue(Integer.parseInt(stateValue));
		}
		if(NumberUtils.isNumber(payChannelValue)){
			recharge.setPayChannelValue(Integer.parseInt(payChannelValue));
		}
		if(!StringUtils.isEmpty(transactionNo)){
			recharge.setTransactionNo(transactionNo.trim());
		}
		pageview=rechargeDao.queryPageView(pageNo, pageSize,recharge);

		if (pageview != null){
			map.put("datas",convertList(pageview.getRecords()));
			map.put("recordsTotal", pageview.getRowCount());
			map.put("totalPage", pageview.getPageCount());
			map.put("pageNow", pageview.getPageNow());
			map.put("code",1);
			map.put("msg","success");
		}
		return  new JSONObject(map).toString();
	}
	/*
	*zlq
	* 查询所有用户的充值记录
	* @param  token
	* @param  page:页码
	* @param  userName:用户名
	* @param  stateValue:状态值
	* @param  payChannelValue：支付渠道值
	* @param  code：编号
	* @param transactionNo:交易流水号
	*
	 */
	public String getAllRechargeRecord(ModelMap map ,String page, String token ,String  userName ,String stateValue,String payChannelValue,String code,String transactionNo){
		Recharge recharge =new Recharge();
		PageView pageview =new  PageView();
		int pageNo = 1;
		int pageSize=20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		recharge.setUserId(loginUser.getId());

		if(NumberUtils.isNumber(userName)){
			User user=userDao.getByName(userName.trim());
			if(user!=null){
				recharge.setUserId(user.getId());
			}
		}
		if(!StringUtils.isEmpty(code)){
			recharge.setCode(code.trim());
		}
		if(NumberUtils.isNumber(stateValue)){
			recharge.setOrderStateValue(Integer.parseInt(stateValue));
		}
		if(NumberUtils.isNumber(payChannelValue)){
			recharge.setPayChannelValue(Integer.parseInt(payChannelValue));
		}
		if(!StringUtils.isEmpty(transactionNo)){
			recharge.setTransactionNo(transactionNo.trim());
		}
		pageview=rechargeDao.queryPageView(pageNo, pageSize,recharge);

		if (pageview != null){
			map.put("datas",convertList(pageview.getRecords()));
			map.put("recordsTotal", pageview.getRowCount());
			map.put("totalPage", pageview.getPageCount());
			map.put("pageNow", pageview.getPageNow());
			map.put("code",1);
			map.put("msg","success");
		}
		return  new JSONObject(map).toString();
	}
	public List<ModelMap> convertList(List<Recharge> rechargeList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (rechargeList != null && rechargeList.size() > 0) {
			for (Recharge recharge : rechargeList) {
				ModelMap map = buildModelList(recharge);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelList(Recharge recharge) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		ModelMap model = new ModelMap();
		User user=userDao.getById(recharge.getUserId());
		model.put("id",recharge.getId());
		model.put("userAccount",recharge.getPhone());
		model.put("flux",recharge.getFlux());
		model.put("code",recharge.getCode());
		model.put("transactionNo",recharge.getTransactionNo()!=null? recharge.getTransactionNo():"");
		model.put("money",recharge.getMoney());
		model.put("state",recharge.getOrderState().toString());
		if(recharge.getPayChannel()!=null){
			model.put("payChannel",recharge.getPayChannel().toString());
		}else {
			model.put("payChannel","");
		}
		model.put("createTime",formatter.format(recharge.getCreateTime()));
		if(recharge.getCancleTime()!=null){
			model.put("cancleTime",formatter.format(recharge.getCancleTime()));
		}else {
			model.put("cancleTime","");
		}
		if(recharge.getPayTime()!=null){
			model.put("payTime",formatter.format(recharge.getPayTime()));
		}else {
			model.put("payTime","");
		}
		return  model;
	}


}